package com.goscom.app.deeset;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import com.goscom.app.database.DBAdapter;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

public class UploadData extends Activity {

	private DBAdapter mDB;
	private String strMerId = "", strUsername;
	private TextView mTxtData, mTxtPic1, mTxtPic2, mTxtPic3, mTxtPic4,
			mTxtSign;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Window window = getWindow();
		window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		setContentView(R.layout.upload_data);

		mTxtPic1 = (TextView) findViewById(R.id.txtUploadDataPic1);
		mTxtPic2 = (TextView) findViewById(R.id.txtUploadDataPic2);
		mTxtPic3 = (TextView) findViewById(R.id.txtUploadDataPic3);
		mTxtPic4 = (TextView) findViewById(R.id.txtUploadDataPic4);
		mTxtSign = (TextView) findViewById(R.id.txtUploadDataSign);
		mTxtData = (TextView) findViewById(R.id.txtUploadData);

		mDB = new DBAdapter(UploadData.this);
		mDB.open();

		getMerId();
	}

	public void getMerId() {
		strMerId = getIntent().getStringExtra("merid");

		ContentValues content = mDB.queryDataByMerId("MER", strMerId);
		content = mDB.queryUserById(content.getAsString("userid"));
		strUsername = content.getAsString("username");

		content = mDB.queryDataByMerId("CONTRACTUAL", strMerId);
		if (content.getAsString("upload") != null
				&& content.getAsString("upload").equals("1")) {
			mTxtSign.setText("Signature: uploaded");
		}

		content = mDB.queryDataByMerId("UPLOAD", strMerId);
		if (content.getAsString("upload1") != null
				&& content.getAsString("upload1").equals("1")) {
			mTxtPic1.setText("Colleague 1: uploaded");
		}
		if (content.getAsString("upload2") != null
				&& content.getAsString("upload2").equals("1")) {
			mTxtPic2.setText("Colleague 2: uploaded");
		}
		if (content.getAsString("upload3") != null
				&& content.getAsString("upload3").equals("1")) {
			mTxtPic3.setText("Colleague 3: uploaded");
		}
		if (content.getAsString("upload4") != null
				&& content.getAsString("upload4").equals("1")) {
			mTxtPic4.setText("Colleague 4: uploaded");
		}
	}

	public void uploadData(View v) {
		SendData sendData = new SendData(this, strMerId, mDB);
		sendData.execute(strUsername);
	}

	public void uploadColleague1(View v) {
		String strAttchUpload1 = Environment.getExternalStorageDirectory()
				+ File.separator + "DCMI" + File.separator + "Camera"
				+ File.separator + strMerId + "-colleague1.jpg";
		File fileUpload = new File(strAttchUpload1);
		if (fileUpload.exists()) {
			if (mDB != null) {
				mDB.close();
			}
			SendPicture sendPicture = new SendPicture(this, 1);
			sendPicture.execute(strAttchUpload1);
		} else {
			Toast.makeText(this, "Can't find file colleague 1!",
					Toast.LENGTH_SHORT).show();
		}
	}

	public void uploadColleague2(View v) {
		String strAttchUpload2 = Environment.getExternalStorageDirectory()
				+ File.separator + "DCMI" + File.separator + "Camera"
				+ File.separator + strMerId + "-colleague2.jpg";
		File fileUpload = new File(strAttchUpload2);
		if (fileUpload.exists()) {
			if (mDB != null) {
				mDB.close();
			}
			SendPicture sendPicture = new SendPicture(this, 2);
			sendPicture.execute(strAttchUpload2);
		} else {
			Toast.makeText(this, "Can't find file colleague 2!",
					Toast.LENGTH_SHORT).show();
		}
	}

	public void uploadColleague3(View v) {
		String strAttchUpload3 = Environment.getExternalStorageDirectory()
				+ File.separator + "DCMI" + File.separator + "Camera"
				+ File.separator + strMerId + "-colleague3.jpg";
		File fileUpload = new File(strAttchUpload3);
		if (fileUpload.exists()) {
			if (mDB != null) {
				mDB.close();
			}
			SendPicture sendPicture = new SendPicture(this, 3);
			sendPicture.execute(strAttchUpload3);
		} else {
			Toast.makeText(this, "Can't find file colleague 3!",
					Toast.LENGTH_SHORT).show();
		}
	}

	public void uploadColleague4(View v) {
		String strAttchUpload4 = Environment.getExternalStorageDirectory()
				+ File.separator + "DCMI" + File.separator + "Camera"
				+ File.separator + strMerId + "-colleague4.jpg";
		File fileUpload = new File(strAttchUpload4);
		if (fileUpload.exists()) {
			if (mDB != null) {
				mDB.close();
			}
			SendPicture sendPicture = new SendPicture(this, 4);
			sendPicture.execute(strAttchUpload4);
		} else {
			Toast.makeText(this, "Can't find file colleague 4!",
					Toast.LENGTH_SHORT).show();
		}
	}

	public void uploadSignature(View v) {
		String strAttchSign = Environment.getExternalStorageDirectory()
				+ File.separator + "DCMI" + File.separator + strMerId
				+ "-signature.png";
		File fileUpload = new File(strAttchSign);
		if (fileUpload.exists()) {
			if (mDB != null) {
				mDB.close();
			}
			SendPicture sendPicture = new SendPicture(this, 0);
			sendPicture.execute(strAttchSign);
		} else {
			Toast.makeText(this, "Can't find file signature!",
					Toast.LENGTH_SHORT).show();
		}
	}

	public void Home(View v) {
		if (mDB != null) {
			mDB.close();
		}
		startActivity(new Intent(UploadData.this, Welcome.class));
	}

	public void Logout(View v) {
		if (mDB != null) {
			mDB.close();
		}
		startActivity(new Intent(UploadData.this, Login.class));
	}

	@Override
	protected void onRestart() {
		mDB.open();
		super.onRestart();
	}

	@Override
	protected void onDestroy() {
		if (mDB != null) {
			mDB.close();
		}
		super.onDestroy();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.login, menu);
		return true;
	}

	/*
	 * @Override public boolean onOptionsItemSelected(MenuItem item) { switch
	 * (item.getItemId()) { case R.id.action_settings: backupToExternal();
	 * break;
	 * 
	 * default: break; } return super.onOptionsItemSelected(item); }
	 */

	private void backupToExternal() {
		// backup db from internal to external
		try {
			File sd = Environment.getExternalStorageDirectory();
			File data = Environment.getDataDirectory();

			if (sd.canWrite()) {
				String currentDBPath = "//data//com.goscom.app.deeset//databases//deeset";
				String backupDBPath = "deeset";
				File currentDB = new File(data, currentDBPath);
				File backupDB = new File(sd, backupDBPath);

				if (currentDB.exists()) {
					FileChannel src = new FileInputStream(currentDB)
							.getChannel();
					FileChannel dst = new FileOutputStream(backupDB)
							.getChannel();
					dst.transferFrom(src, 0, src.size());
					src.close();
					dst.close();
				}
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public class SendData extends AsyncTask<String, Integer, Boolean> {

		private Context mCtx;
		private String mStrMerId;
		private DBAdapter mDB;
		private ProgressDialog mProgress;

		public SendData(Context ctx, String strMerId, DBAdapter mDB) {
			this.mCtx = ctx;
			this.mStrMerId = strMerId;
			this.mDB = mDB;
			mProgress = new ProgressDialog(ctx);
		}

		@Override
		protected Boolean doInBackground(String... params) {
			Log.i("Username", params[0]);
			CollectData collectData = new CollectData(mCtx, params[0],
					mStrMerId, mDB);
			collectData.execute(mStrMerId);
			try {
				if (collectData.get()) {
					mDB.close();
					String strFileData = "/mnt/sdcard/DCMI/" + mStrMerId
							+ "-merchandiser.txt";
					String strResult;
					do {
						strResult = uploadFile(strFileData, mCtx);
					} while (strResult.equals("fail") == true);
					return true;
				}
			} catch (InterruptedException e) {
				Log.i("InterruptedException Data", e.getMessage());
			} catch (ExecutionException e) {
				Log.i("ExecutionException Data", e.getMessage());
			}
			return false;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			mProgress.dismiss();
			if (result) {
				mTxtData.setText("Data: upload success");
			} else {
				mTxtData.setText("Data: upload fail");
			}
			super.onPostExecute(result);
		}

		@Override
		protected void onPreExecute() {
			mProgress.setIcon(android.R.drawable.stat_sys_upload);
			mProgress.setTitle("Upload data");
			mProgress.setMessage("Uploading...");
			mProgress.setCancelable(false);
			mProgress.setCanceledOnTouchOutside(false);
			mProgress.show();
			super.onPreExecute();
		}
	}

	private String uploadFile(String strPath, Context ctx) {
		UploadFile upload = new UploadFile(ctx, strUsername, strMerId);
		upload.execute(strPath);
		try {
			if (upload.get(60, TimeUnit.SECONDS)) {
				Log.i("Upload", "Successful!");
				return "success";
			}
		} catch (InterruptedException e) {
			Log.i("InterruptedException Data", e.getMessage());
		} catch (ExecutionException e) {
			Log.i("ExecutionException Data", e.getMessage());
		} catch (TimeoutException e) {
			return "fail";
		}
		return "fail";
	}

	public class SendPicture extends AsyncTask<String, Integer, Boolean> {

		private Context mCtx;
		private int mIntOrder;
		private ProgressDialog mProgress;

		public SendPicture(Context ctx, int intOrder) {
			this.mCtx = ctx;
			this.mIntOrder = intOrder;
			mProgress = new ProgressDialog(ctx);
		}

		@Override
		protected Boolean doInBackground(String... params) {
			String strResult;
			do {
				strResult = uploadFile(params[0], mCtx);
			} while (strResult.equals("fail") == true);
			return true;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			mProgress.dismiss();
			mDB.open();
			ContentValues content = new ContentValues();
			switch (mIntOrder) {
			case 0:
				content.put("upload", "1");
				mDB.updateUploadPic("CONTRACTUAL", strMerId, content);
				mTxtSign.setText("Signature: upload success");
				break;
			case 1:
				content.put("upload1", "1");
				mDB.updateUploadPic("UPLOAD", strMerId, content);
				mTxtPic1.setText("Colleague 1: upload success");
				break;
			case 2:
				content.put("upload2", "1");
				mDB.updateUploadPic("UPLOAD", strMerId, content);
				mTxtPic2.setText("Colleague 2: upload success");
				break;
			case 3:
				content.put("upload3", "1");
				mDB.updateUploadPic("UPLOAD", strMerId, content);
				mTxtPic3.setText("Colleague 3: upload success");
				break;
			case 4:
				content.put("upload4", "1");
				mDB.updateUploadPic("UPLOAD", strMerId, content);
				mTxtPic4.setText("Colleague 4: upload success");
				break;
			default:
				break;
			}
			super.onPostExecute(result);
		}

		@Override
		protected void onPreExecute() {
			mProgress.setIcon(android.R.drawable.stat_sys_upload);
			mProgress.setTitle("Upload data");
			mProgress.setMessage("Uploading...");
			mProgress.setCancelable(false);
			mProgress.setCanceledOnTouchOutside(false);
			mProgress.show();
			super.onPreExecute();
		}
	}

}
